<template>
  <canvas
    id="canvas"
    class="canvas"
  />
</template>

<script>
import { fabric } from 'fabric'
// import http from '../assets/js/http'
export default {
  name: 'CanvasImg',
  props: {
    datas: {
      type: Array,
      default: () => []
    }
  },
  data () {
    return {
      canvas: null
    }
  },
  mounted () {
    setTimeout(() => {
      this.canvas = new fabric.Canvas('canvas', {
        backgroundColor: 'transparent',
        width: 300,
        height: 500,
        preserveObjectStacking: true,
        imageSmoothingEnabled: false,
        enableRetinaScaling: false,
        fireRightClick: true,
        stopContextMenu: true
      })
      this.canvas.selection = false
      const drawCLothes = (img) => {
        fabric.Image.fromURL(img, (img) => {
          img.scaleToHeight(this.canvas.height - 200)
          // img.set('selectable', false)
          img.set({
            // 通过scale来设置图片大小，这里设置和画布一样大
            left: this.canvas.width / 2 - img.width * img.scaleX / 2,
            top: this.canvas.height / 2 - img.height * img.scaleX / 2,
            cornerStyle: 'circle',
            cornerSize: 20,
            originX: 'center',
            originY: 'center'
          }).setControlsVisibility({ // 这个方法是重点
            mb: false,
            ml: false,
            mr: false,
            mt: false
          })
          this.canvas.add(img).setActiveObject(img)
        })
      }

      fabric.Image.fromURL(this.datas[0].img, async (imgs) => {
        imgs.scaleToWidth(100)
        // imgs.set('selectable', false)
        imgs.set({
          left: this.canvas.width / 2 - imgs.width * imgs.scaleX / 2 + this.datas[0].location.left,
          top: 10,
          cornerStyle: 'circle',
          cornerSize: 20,
          originX: 'center',
          originY: 'center'
        }).setControlsVisibility({ // 这个方法是重点
          mb: false,
          ml: false,
          mr: false,
          mt: false
        })
        this.canvas.add(imgs).setActiveObject(imgs)
        drawCLothes(this.datas[1].img)
      })
    }, 0)
  },
  methods: {
    getBase64 () {
      return new Promise((resolve, reject) => {
        const canvasToImg = document.getElementById('canvas')
        const dataURL = canvasToImg.toDataURL('image/png', 1) // 获取Base64编码
        resolve(dataURL)
      })
    }
  }
}
</script>

<style scoped>
  .canvas{
    width: 100%;
    height: 100%;
  }
</style>
